﻿
//using Dapper;
//using Infrastructure.Enums;
//using Infrastructure;
//using System;
//using System.Collections.Generic;
//using System.ComponentModel.DataAnnotations;
//using System.Data;
//using System.Data.SqlClient;
//using System.IO;
//using System.Linq;
//using System.Linq.Expressions;
//using System.Text;
//using Infrastructure.Extensions;
//using Infrastructure.WebApi;

//namespace Infrastructure.Dapper
//{
//    public class SqlDapper : ISqlDapper
//    {
//        private string _connectionString;
//        private string _dbType;
//        private int? commandTimeout = null;

//        public SqlDapper()
//        {
//            _connectionString = Config.ReadSetting("Connection:DbConnectionString");
//            _dbType = Config.ReadSetting("Connection:DBType");
//        }

//        /// <summary>
//        /// 构造函数
//        /// </summary>
//        /// <param name="connectionString">链接字符串</param>
//        /// <param name="dbType">数据库类型</param>
//        public SqlDapper(string connectionString, string dbType = "MsSql")
//        {
//            _connectionString = connectionString;
//            _dbType = dbType;
//        }


//        private bool _transaction { get; set; }

//        private IDbConnection _transactionConnection = null;

//        /// <summary>
//        /// 超时时间(秒)
//        /// </summary>
//        /// <param name="timeout"></param>
//        /// <returns></returns>
//        public ISqlDapper SetTimout(int timeout)
//        {
//            this.commandTimeout = timeout;
//            return this;
//        }

//        /// <summary>
//        /// 2020.06.15增加Dapper事务处理
//        /// <param name="action"></param>
//        /// <param name="error"></param>
//        public void BeginTransaction(Func<ISqlDapper, bool> action, Action<Exception> error)
//        {
//            _transaction = true;
//            using (var connection = new SqlConnection(_connectionString))
//            {
//                try
//                {
//                    _transactionConnection = connection;
//                    _transactionConnection.Open();
//                    dbTransaction = _transactionConnection.BeginTransaction();
//                    bool result = action(this);
//                    if (result)
//                    {
//                        dbTransaction?.Commit();
//                    }
//                    else
//                    {
//                        dbTransaction?.Rollback();
//                    }
//                }
//                catch (Exception ex)
//                {
//                    dbTransaction?.Rollback();
//                    error(ex);
//                }
//                finally
//                {
//                    _transaction = false;
//                    dbTransaction?.Dispose();
//                }
//            }
//        }

//        /// <summary>
//        /// 执行sql语句
//        /// </summary>
//        /// <param name="cmd"></param>
//        /// <param name="param"></param>
//        /// <param name="commandType"></param>
//        /// <param name="beginTransaction"></param>
//        /// <returns></returns>
//        public int ExcuteNonQuery(string cmd, object param, CommandType? commandType = null, bool beginTransaction = false)
//        {
//            return Execute<int>((conn, dbTransaction) =>
//            {
//                return conn.Execute(cmd, param, dbTransaction, commandType: commandType ?? CommandType.Text, commandTimeout: commandTimeout);
//            }, beginTransaction);
//        }

//        /// <summary>
//        /// 查询第一行第一列数据
//        /// </summary>
//        /// <param name="cmd"></param>
//        /// <param name="param"></param>
//        /// <param name="commandType"></param>
//        /// <param name="beginTransaction"></param>
//        /// <returns></returns>
//        public object ExecuteScalar(string cmd, object param, CommandType? commandType = null, bool beginTransaction = false)
//        {
//            return Execute<object>((conn, dbTransaction) =>
//            {
//                return conn.ExecuteScalar(cmd, param, dbTransaction, commandType: commandType ?? CommandType.Text, commandTimeout: commandTimeout);
//            }, beginTransaction);
//        }

//        #region search


//        /// <summary>
//        /// 查询数据
//        /// </summary>
//        /// <typeparam name="T">查询对象</typeparam>
//        /// <param name="cmd">sql语句</param>
//        /// <param name="param"></param>
//        /// <param name="commandType"></param>
//        /// <param name="beginTransaction"></param>
//        /// <returns></returns>
//        public List<T> QueryList<T>(string cmd, object param, CommandType? commandType = null, bool beginTransaction = false) where T : class
//        {
//            return Execute((conn, dbTransaction) =>
//            {
//                return conn.Query<T>(cmd, param, dbTransaction, commandType: commandType ?? CommandType.Text, commandTimeout: commandTimeout).ToList();
//            }, beginTransaction);
//        }


//        /// <summary>
//        /// 查询第一条数据
//        /// </summary>
//        /// <typeparam name="T"></typeparam>
//        /// <param name="cmd"></param>
//        /// <param name="param"></param>
//        /// <param name="commandType"></param>
//        /// <param name="beginTransaction"></param>
//        /// <returns></returns>
//        public T QueryFirst<T>(string cmd, object param, CommandType? commandType = null, bool beginTransaction = false) where T : class
//        {
//            return QueryList<T>(cmd, param, commandType: commandType ?? CommandType.Text, beginTransaction: beginTransaction).FirstOrDefault();
//        }

//        /// <summary>
//        /// 添加数据 
//        /// </summary>
//        /// <typeparam name="T"></typeparam>
//        /// <param name="entity"></param>
//        /// <param name="addFileds"></param>
//        /// <param name="beginTransaction"></param>
//        /// <returns></returns>
//        public int Insert<T>(T entity, bool beginTransaction = false)
//        {
//            return AddRange<T>(new T[] { entity }, beginTransaction);
//        }

//        #endregion

//        #region insert 

//        /// <summary>
//        /// 批量添加数据 
//        /// </summary>
//        /// <typeparam name="T"></typeparam>
//        /// <param name="entity"></param>
//        /// <param name="addFileds"></param>
//        /// <param name="beginTransaction"></param>
//        /// <returns></returns>
//        public int Insert<T>(IEnumerable<T> entity, bool beginTransaction = false)
//        {
//            return AddRange<T>(entity, beginTransaction);
//        }

//        /// <summary>
//        /// 批量添加
//        /// </summary>
//        /// <typeparam name="T"></typeparam>
//        /// <param name="entities"></param>
//        /// <param name="updateFileds"></param>
//        /// <param name="beginTransaction"></param>
//        /// <returns></returns>
//        private int AddRange<T>(IEnumerable<T> entities, bool beginTransaction = false)
//        {

//            Type entityType = typeof(T);

//            //获取主键
//            var key = entityType.GetKeyProperty();
//            if (key == null)
//            {
//                throw new Exception("实体必须包括主键才能批量操作");
//            }

//            string[] columns;


//            var properties = entityType.GetProperties().GetGenericProperties();
//            //if (key.PropertyType != typeof(string))
//            //{
//            //    properties = properties.Where(x => x.Name != key.Name).ToArray();
//            //}
//            columns = properties.Select(x => x.Name).ToArray();

//            string sql = $"insert into {entityType.Name}([{string.Join("],[", columns)}])" +
//                 $"values(@{string.Join(",@", columns)});";


//            return Execute<int>((conn, dbTransaction) =>
//            {
//                return conn.Execute(sql, (_dbType == DbCurrentType.MsSql.ToString()) ? entities.ToList() : null, dbTransaction);
//            }, beginTransaction);
//        }
//        #endregion

//        #region update

//        public int Update<T>(T entity, Expression<Func<T, object>> updateFileds = null, bool beginTransaction = false)
//        {
//            return UpdateRange<T>(new T[] { entity }, updateFileds, beginTransaction);
//        }
//        public int Update<T>(IEnumerable<T> entities, Expression<Func<T, object>> updateFileds = null, bool beginTransaction = false)
//        {
//            return UpdateRange<T>(entities, updateFileds, beginTransaction);
//        }

//        private int UpdateRange<T>(IEnumerable<T> entities, Expression<Func<T, object>> updateFileds = null, bool beginTransaction = false)
//        {
//            Type entityType = typeof(T);
//            var key = entityType.GetKeyProperty();
//            if (key == null)
//            {
//                throw new Exception("实体必须包括主键才能批量更新");
//            }

//            var properties = entityType.GetGenericProperties()
//            .Where(x => x.Name != key.Name);
//            if (updateFileds != null)
//            {
//                properties = properties.Where(x => updateFileds.GetExpressionToArray().Contains(x.Name));
//            }

//            List<string> paramsList = new List<string>();
//            foreach (var item in properties)
//            {
//                paramsList.Add($"[{item.Name}]=@" + item.Name);
//            }
//            string sqltext = $@"update { entityType.Name} set {string.Join(",", paramsList)} where {entityType.GetKeyName()} = @{entityType.GetKeyName()} ;";

//            return ExcuteNonQuery(sqltext, entities, CommandType.Text, true);
//        }

//        #endregion

//        #region delete


//        public int Delete<T>(string key)
//        {
//            return DeleteRange<T>(new List<string> { key });
//        }
//        public int Delete<T>(IEnumerable<string> keys)
//        {
//            return DeleteRange<T>(keys);
//        }

//        private int DeleteRange<T>(IEnumerable<string> keys)
//        {
//            Type entityType = typeof(T);
//            var keyProperty = entityType.GetKeyProperty();
//            if (keyProperty == null || keys == null || keys.Count() == 0) return 0;

//            string tKey = keyProperty.Name;
//            FieldType fieldType = entityType.GetFieldType();
//            string joinKeys = (fieldType == FieldType.Int || fieldType == FieldType.BigInt)
//                 ? string.Join(",", keys)
//                 : $"'{string.Join("','", keys)}'";


//            string sql = $"delete from {entityType.Name } where {tKey} in ({joinKeys});";

//            return ExcuteNonQuery(sql, null);
//        }

//        #endregion

//        #region Private  Method

//        /// <summary>
//        /// 针对解析出查询条件
//        /// </summary>
//        /// <typeparam name="T">查询对象</typeparam>
//        /// <param name="req">查询条件对象</param>
//        /// <param name="notPage">是否分页查询</param>
//        /// <returns></returns>
//        public string tableSql<T>(Request req, bool notPage = false)
//        {
//            Type entityType = typeof(T);
//            var tableName = entityType.Name;
//            var keyName = entityType.GetKeyName();

//            var condition = string.Empty;
//            var columns = notPage ? " count(*)" : " * ";

//            //检索查询条件等关键因素
//            if (req.Json != null)
//            {
//                var msg = ConvertJsonExtension.DeserializeObject(Convert.ToString(req.Json), out Query format);
//                if (msg == "OK")
//                {
//                    //索引条件/ 排序
//                    condition += $" {(string.IsNullOrEmpty(format.Condition) ? "" : " and ") + format.Condition} ";
//                    //排序
//                    var order = $" Order by {(string.IsNullOrEmpty(format.Order) ? keyName : format.Order)} ";

//                    if (!notPage) { condition += order; }

//                    //分页
//                    if (!notPage && format.NotPage && !string.IsNullOrEmpty(format.CurrentPage) && !string.IsNullOrEmpty(format.PageSize))
//                    {
//                        var page = format.CurrentPage.ToInt(1);
//                        var pageSize = format.PageSize.ToInt(10);
//                        condition += $"offset({(page - 1) * pageSize}) rows fetch next {pageSize} rows only;";
//                    }

//                    //显示字段
//                    if (!notPage && !string.IsNullOrEmpty(format.Select))
//                    {
//                        columns = format.Select;
//                    }
//                }
//            }

//            string tableSql = $" select {columns} from {tableName} where 1=1 {condition} ";
//            return tableSql;
//        }

//        IDbTransaction dbTransaction = null;
//        private T Execute<T>(Func<IDbConnection, IDbTransaction, T> func, bool beginTransaction = false)
//        {
//            if (_transaction)
//            {
//                return func(_transactionConnection, dbTransaction);
//            }
//            if (beginTransaction)
//            {
//                return ExecuteTransaction(func);
//            }
//            using (var connection = new SqlConnection(_connectionString))
//            {
//                return func(connection, dbTransaction);
//            }
//        }

//        /// <summary>
//        /// 开启事务添加
//        /// </summary>
//        /// <typeparam name="T"></typeparam>
//        /// <param name="func"></param>
//        /// <returns></returns>
//        private T ExecuteTransaction<T>(Func<IDbConnection, IDbTransaction, T> func)
//        {
//            using (_transactionConnection = new SqlConnection(_connectionString))
//            {
//                try
//                {
//                    _transactionConnection.Open();
//                    dbTransaction = _transactionConnection.BeginTransaction();
//                    T reslutT = func(_transactionConnection, dbTransaction);
//                    dbTransaction.Commit();
//                    return reslutT;
//                }
//                catch (Exception ex)
//                {
//                    dbTransaction?.Rollback();
//                    throw ex;
//                }
//                finally
//                {
//                    dbTransaction?.Dispose();
//                }
//            }
//        }

//        #endregion

//    }
//}
